package com.hxzy.controller.anonymous.code;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.hxzy.common.constans.RedisConstans;
import com.hxzy.common.resp.R;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author wy
 * @Description 验证码
 * @Date 2023/8/28 15:47
 * @Version 1.0
 */
@Api(tags = "公共API-验证码")
@RestController
@RequestMapping(value = "/anon")
public class CodeController {

    @Autowired
    private RedisTemplate  redisTemplate;


    @ApiOperation(value = "获取验证码")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "width",value = "图片宽度"),
            @ApiImplicitParam(name = "height",value = "图片高度"),
            @ApiImplicitParam(name = "len",value = "图片长度"),
            @ApiImplicitParam(name = "type",value = "验证码类型(png,gif,airth)"),
    })
    @GetMapping(value = "/code")
    public R codeApi(@RequestParam(value = "width",defaultValue = "130",required = false) Integer width,
                     @RequestParam(value = "height",defaultValue = "34",required = false) Integer height,
                     @RequestParam(value = "len",defaultValue = "2",required = false) Integer len,
                     @RequestParam(value = "type",defaultValue = "airth",required = false) String type){
          //多态    简单工厂
        Captcha  captcha=null;
        if(type.equalsIgnoreCase("png")){
            captcha=new SpecCaptcha(width,height);
        }else if(type.equalsIgnoreCase("gif")){
            captcha=new GifCaptcha(width,height);
        }else if(type.equalsIgnoreCase("airth")){
            captcha=new ArithmeticCaptcha(width,height);
        }
        captcha.setLen(len);

        //取得验证码
        String code=captcha.text();
        //得到图片(base64位的字符)
        String base64Image=captcha.toBase64();

        String uuid = UUID.randomUUID().toString();

        //前后端分离项目建议不要存储在session中，要把值存储到（数据库，缓存分布式 redis, mongodb）
        String redisKey= RedisConstans.getRedisKey(RedisConstans.CAPTCHA_KEY, uuid);
        this.redisTemplate.opsForValue().set(redisKey,code,RedisConstans.CAPTCHA_EXPIRED_MINUTE, TimeUnit.MINUTES);

        Map<String,String>  dataMap=new HashMap<>();
        dataMap.put("uuid",uuid);
        dataMap.put("image",base64Image);
        return R.okHasData(dataMap);
    }

    @ApiOperation(value = "生成二维码")
    @GetMapping(value = "/qrcode")
    public void writeQrCode(String url, HttpServletResponse resp) throws IOException {
        QrConfig config = new QrConfig(300, 300);
       // 设置边距，既二维码和背景之间的边距
        config.setMargin(3);
        // 设置前景色，既二维码颜色（青色）
        config.setForeColor(Color.CYAN.getRGB());
         // 设置背景色（灰色）
        config.setBackColor(Color.GRAY.getRGB());

         // 生成二维码到文件，也可以到流
        QrCodeUtil.generate(url,config, ImgUtil.IMAGE_TYPE_PNG,resp.getOutputStream());
    }

}
